<template>
    <div>
        <el-form ref="form" :model="d" label-width="80px">
            <el-form-item label="登录名" prop="uname" :rules="[formRulesMixin.notNull]">
                <el-input v-model="d.uname" clearable autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name" :rules="[formRulesMixin.notNull]">
                <el-input v-model="d.name" clearable autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile" :rules="[formRulesMixin.notNull]">
                <el-input v-model="d.mobile" clearable autocomplete="off" maxlength="11" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="pass" :rules="[ { required: d.manager_id==0, message: '密码不能为空'} ]" v-show="d.manager_id==0">
                <el-input v-model="d.pass" clearable autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="权限">
                <div class="checkboxgroup">
                    <div v-for="(a,a_index) in d.menu" :key="a_index" class="item">
                        <div class="flex-row-center">
                            <el-checkbox v-model="a.checked" :indeterminate="a.indeterminate" class="checkbox1" @change="itemChange($event, a)">{{a.label}}</el-checkbox>
                            <div :class="[a.chirldShow?'bottom_icon':'right_icon', 'pointer', 'ml5', 'mini-gray-size']" @click="a.chirldShow=!a.chirldShow"></div>
                        </div>
                        <div class="subdiv" v-show="a.chirldShow">
                            <div class="subitem" v-for="(b,b_index) in a.sub" :key="b_index">
                                <el-checkbox v-model="b.checked" @change="subItemChange($event, b, a)" class="checkbox1">{{b.label}}</el-checkbox>
                                <div class="subsubitem" v-for="(c,c_index) in b.sub" :key="c_index">
                                    <el-checkbox v-model="c.checked" @change="subSubItemChange($event, c, a)" class="checkbox1">{{c.label}}</el-checkbox>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </el-form-item>
            <el-form-item class="dialog-btns-item">
                <div class="dialog-btns">
                    <span class="btn clear" @click="$emit('close')">取消</span>
                    <span class="btn sub ml10" @click.prevent="upData">提交</span>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { reactive,ref,getCurrentInstance,toRaw,inject } from 'vue'
let { proxy } = getCurrentInstance()
let d = reactive({
    manager_id: inject("id").value || 0,
    uname: "",
    name: "",
    pass: "",
    mobile:"",
    menu: [],
    authority: [],
})

let allMenu = () => {
    return new Promise((resolve, reject) => {
        proxy.$ajax({
            url: 'menu',
            data: {},
            bfLoading: true
        }).then(d => {
            resolve(d.msg)
        }).catch(e => {
            reject(e)
        })
    })
}
let userInfo = () => {
    return new Promise((resolve, reject) => {
        proxy.$ajax({
            url: '/manager/get',
            data: {id: d.manager_id},
            bfLoading: true
        }).then(d => {
            resolve(d.msg)
        }).catch(e => {
            reject(e)
        })
    })
}
let init = async () => {
    let menu = await allMenu()
    let userinfo = {authority:[]}
    if(d.manager_id > 0) userinfo = await userInfo()
    let flag = [] //把所有的权限先给进一个数组
    d.uname = userinfo.uname || ""
    d.name = userinfo.name || ""
    d.mobile = userinfo.mobile
    userinfo.authority.forEach(t => {
        t.sub.forEach(t1 => {
            if(t1.label && t1.component){
                flag.push(t1.component)
                flag.push(t1.component+"/list")
            }
            t1.sub.forEach(ts => {
                if(ts.component)
                    flag.push(t1.component+"/"+ts.component)
            })
        })
    })
    menu.forEach(t => {
        t.checked = false
        t.indeterminate = false
        delete t.url
        // delete t.show //这个删了就不能显示了
        t.sub.forEach(s => {
            s.checked = flag.some(e => s.url == e) //从权限判断是否要勾中
            delete s.url
            // delete s.show
            s.sub.forEach(ts => {
                ts.checked = flag.some(e => ts.url == e) //从权限判断是否要勾中
                delete ts.url
                // delete ts.show
            })
        })
    })
    //这步必须在上一步完成后，才能操作，不能实时做
    menu.forEach(t => {
        let checked = true //是否全选中
        let notchecked = true //是否全没选中
        t.sub.forEach(e => {
            if (!e.checked) checked = false
            if (e.checked) notchecked = false
            e.sub.forEach(es => {
                if(!es.checked) checked = false
                if(es.checked) notchecked = false
            })
        })
        // console.log(t.label, checked, notchecked)
        if(!checked && !notchecked){ //没有全选，也没有全不选
            t.indeterminate = true
            t.checked = false
        }else{
            if(checked){ //全选中
                t.indeterminate = false
                t.checked = true
            }else{ //全部未选中
                t.indeterminate = false
                t.checked = false
            }
        }
        t.chirldShow = false
    })
    console.log(menu);
    d.menu = menu;
}
init()
let parent_check = parent => { //判断顶部状态
    let x = []
    parent.sub.forEach(t => {
        x.push(t.checked)
        t.sub.forEach(p => x.push(p.checked))
    })
    if(x.every(p => p)){ //全部选中就选中，否则就是没选中
        parent.indeterminate = false
        parent.checked = true
    } else if (x.every(p => !p)){
        parent.indeterminate = false
        parent.checked = false
    }else{
        parent.indeterminate = true
    }
}
let itemChange = (e, item) => {
    item.indeterminate = false
    item.sub.forEach(t => {
        t.checked = e
        t.sub.forEach(t1 => t1.checked = e)
    })
}
let subItemChange = (e, item, parent) => { //有一项选中，顶部就半选中
    item.checked = e //0-未选中，1-选中；2-部分选中
    item.sub.forEach(t => t.checked = e) //选中所有子项
    parent_check(parent)
}
let subSubItemChange = (e, item, parent) => { //有一项选中，最顶部就半选中
    item.checked = e
    parent_check(parent)
}
let upData = () => {
    proxy.$refs['form'].validate(valid => {
    if (valid) {
        let tmp = []
        d.menu.forEach(t => {
            if(t.checked || t.indeterminate){ //设备管理
                let {checked,indeterminate,sub,...tmp_t} = t
                tmp_t.sub = []
                t.sub.forEach(ts => {
                    let tmp_c = false //用来判断子项有没有选中的
                    let tmp_ts_sub = [] //子项数组，先放着，在下面先存好，在最下面再赋值
                    ts.sub.forEach(tss => { //先看子项，若有一个子项选中，则主项也必须要加进去才行
                        if(tss.checked){
                            tmp_c = true
                            let {checked,indeterminate,...tmp_tss} = tss
                            tmp_ts_sub.push(tmp_tss)
                        }
                    })
                    if(ts.checked || tmp_c){ //班牌，可能选中，也可能没选中，而没选中也不影响他下面的子类选中
                        let {checked,indeterminate,...tmp_ts} = ts
                        if(!ts.checked){ //如是因为有子项选中，而主项实际未选中，则删除此三项属性
                            delete tmp_ts.label //lable或component有一项删除，服务端即认为没有权限
                            // delete tmp_ts.component //这项若删，则不知道子项的父级是谁，所以只能保留
                            delete tmp_ts.url
                        }
                        tmp_ts.sub = tmp_ts_sub
                        tmp_t.sub.push(tmp_ts)
                    }
                })
                tmp.push(tmp_t)
            }
        });
        d.authority = JSON.stringify(tmp)
        // console.log(d)
        proxy.$ajax({
            url: '/manager/design',
            data: d,
            bfLoading: true
        }).then(data => {
            // console.log(date)
            if(data.success){
                proxy.elMessageMixin(`管理员${d.manager_id>0?'修改':'添加'}成功`, 'success')
                proxy.$emit('close')
                proxy.$emit('init')
            }else{
                ElMessage({ message: data.err, type: 'error', duration: 2 * 1000 })
            }
        }).catch(() => {})
    } else {
      return false
    }
  })
}
</script>

<style scoped>
    .checkboxgroup { padding-top: 5px; }
    .checkbox1 { height:22px; font-weight: normal; }
    .item { padding-bottom: 10px; line-height: 0; }
    .subdiv { display: flex; flex-wrap: wrap; padding-left: 20px; }
    .subitem { padding-left:10px; }
    .subsubitem { padding-left: 30px; }
</style>

